package com.ytkj.digitalConstruction.service.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ytkj.digitalConstruction.dao.role.RoleMapper;
import com.ytkj.digitalConstruction.dao.role.UserGroupRoleMapper;
import com.ytkj.digitalConstruction.dao.user.UserGroupMapper;
import com.ytkj.digitalConstruction.dao.user.UserGroupUserMapper;
import com.ytkj.digitalConstruction.dao.user.UserMapper;
import com.ytkj.digitalConstruction.entity.role.Role;
import com.ytkj.digitalConstruction.entity.role.UserGroupRole;
import com.ytkj.digitalConstruction.entity.user.User;
import com.ytkj.digitalConstruction.entity.user.UserGroup;
import com.ytkj.digitalConstruction.entity.user.UserGroupUser;
import com.ytkj.digitalConstruction.httpbean.user.UserInGroup;
import com.ytkj.digitalConstruction.httpbean.user.req.ReqUserGroup;
import com.ytkj.digitalConstruction.httpbean.user.req.UserListByUserGroupId;
import com.ytkj.digitalConstruction.httpbean.user.resbean.ReturnUserGroup;
import com.ytkj.digitalConstruction.util.WebTokenUtil;

/**
 * 用户组业务处理类
 *
 * @author Pete
 * @Date 2017年12月7日
 */
@Service
public class UserGroupService {

	@Autowired
	private UserGroupMapper userGroupMapper;
	@Autowired
	private UserGroupRoleMapper userGroupRoleMapper;
	@Autowired
	private UserGroupUserMapper userGroupUserMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private UserMapper userMapper;

	/**
	 * 获取用户组管理（读取）
	 * 
	 * @return
	 */
	public List<ReturnUserGroup> getUserGroups(HttpServletRequest request) {
		//查询登陆者的所有用户组
		//从request中获取用户Id
		Integer userId = WebTokenUtil.getUserId(request);
		//查询用户对应的列表
		List<ReturnUserGroup> returnUserGroups = userGroupUserMapper.selectByUserIdPrimaryKeys(userId);
		// 循环用户组，根据单个用户组查询对应的 角色信息
		for (ReturnUserGroup returnUserGroup : returnUserGroups) {
			if(returnUserGroup.getUserGroupDesc()==null) {
				returnUserGroup.setUserGroupDesc("");
			}
			List<UserGroupRole> userGroupRoles = userGroupRoleMapper
					.selectByUserGroupId(returnUserGroup.getUserGroupId());
			List<Role> list = new ArrayList<Role>();
			for (UserGroupRole userGroupRole : userGroupRoles) {
				Role role = roleMapper.selectByPrimaryKey(userGroupRole.getRoleId());
				if (role == null) {
					continue;
				}
				list.add(role);
			}
			returnUserGroup.setRoles(list);
		}
		return returnUserGroups;
	}

	/**
	 * 修改用户组
	 * 
	 * @param reqUserGroup
	 * @return
	 */
	@Transactional
	public boolean updateUserGroups(ReqUserGroup reqUserGroup,HttpServletRequest request) {
		// 更新用户组信息
		UserGroup module = new UserGroup();
		UserGroup userGroup = userGroupMapper.selectByPrimaryKey(reqUserGroup.getUserGroupId());
		if (userGroup == null) {
			return false;
		}
		module.setUserGroupId(reqUserGroup.getUserGroupId());
		module.setUserGroupName(reqUserGroup.getUserGroupName());
		module.setUserGroupDesc(("".equals(reqUserGroup.getUserGroupDesc()) || reqUserGroup.getUserGroupDesc() == null)
				? module.getUserGroupDesc()
				: reqUserGroup.getUserGroupDesc());
		userGroupMapper.updateByPrimaryKey(module);
		//删除关联表数据
		List<UserGroupUser> userGroupUsers = userGroupUserMapper.selectByUserGroupId(reqUserGroup.getUserGroupId());
		if (userGroupUsers.size() > 0) {
			userGroupUserMapper.batchDelete(userGroupUsers);
		}
		// 更新用户组和角色的关联表 1.删除关联 2.新增关联
		List<UserGroupRole> userGroupRoles = userGroupRoleMapper.selectByUserGroupId(reqUserGroup.getUserGroupId());
		if (userGroupRoles.size() > 0) {
			userGroupRoleMapper.batchDelete(userGroupRoles);
		}
		List<UserGroupRole> ugrList = new ArrayList<>();
		for (String userId : reqUserGroup.getRoleIds()) {
			UserGroupRole obj = new UserGroupRole();
			obj.setRoleId(Integer.valueOf(userId));
			obj.setUserGroupId(reqUserGroup.getUserGroupId());
			ugrList.add(obj);
		}
		if (ugrList.size() > 0) {
			userGroupRoleMapper.batchInsert(ugrList);
		}
		UserGroupUser user = new UserGroupUser();
		Integer userId = WebTokenUtil.getUserId(request);
		user.setUserId(userId);
		user.setUserGroupId(module.getUserGroupId());
		userGroupUserMapper.insert(user);
		// 更新用户组和用户的关联表 1.删除关联 2.新增关联
		/*List<UserGroupUser> lists = new ArrayList<>();
		for (String userIds : reqUserGroup.getUsereIds()) {
			UserGroupUser obj = new UserGroupUser();
			obj.setUserId(Integer.valueOf(userIds));
			obj.setUserGroupId(module.getUserGroupId());
			lists.add(obj);
		}
		if (lists.size() > 0) {
			userGroupUserMapper.batchInsert(lists);
		}*/
		return true;
	}

	/**
	 * 新增用户组
	 *
	 * @param reqUserGroup
	 * @return
	 */
	@Transactional
	public boolean insertUserGroup(ReqUserGroup reqUserGroup,HttpServletRequest request) {
		UserGroup module = new UserGroup();
		module.setUserGroupName(reqUserGroup.getUserGroupName());
		module.setUserGroupDesc("".equals(reqUserGroup.getUserGroupDesc()) ? "" : reqUserGroup.getUserGroupDesc());
		int rows = userGroupMapper.insertSelective(module);
		if (rows > 0) {
			reqUserGroup.setUserGroupId(module.getUserGroupId());
		}
		//从request中获取用户Id
		Integer userId = WebTokenUtil.getUserId(request);
		UserGroupUser users = new UserGroupUser();  
		users.setUserId(userId);
		users.setUserGroupId(module.getUserGroupId());
		userGroupUserMapper.insert(users);
		//添加关联表人员
		List<UserGroupUser> ugrLists = new ArrayList<>();
		for (String userIds : reqUserGroup.getUsereIds()) {
			UserGroupUser userGroupUser = new UserGroupUser();
			if(userIds == null) {
				continue;
			}
			userGroupUser.setUserGroupId(reqUserGroup.getUserGroupId());
			userGroupUser.setUserId(Integer.valueOf(userIds));
			Integer user = userGroupUserMapper.selectByUserIdPrimaryKey(userGroupUser);
			if (user == null) {
				ugrLists.add(userGroupUser);
			}
		}
		if (ugrLists.size() > 0) {
			userGroupUserMapper.batchInsert(ugrLists);
		}
		
		// 建立用户组与角色的关联关系
		List<UserGroupRole> ugrList = new ArrayList<>();
		for (String userIds : reqUserGroup.getRoleIds()) {
			UserGroupRole obj = new UserGroupRole();
			obj.setRoleId(Integer.valueOf(userIds));
			obj.setUserGroupId(module.getUserGroupId());
			ugrList.add(obj);
		}
		if (ugrList.size() > 0) {
			userGroupRoleMapper.batchInsert(ugrList);
		}
		return true;
	}

	/**
	 * 删除用户组
	 * 
	 * @param userGroupId
	 * @return
	 */
	@Transactional
	public boolean deleteUserGroup(Integer userGroupId) {
		// 删除用户组,同时删除用户组与用户的关联关系
		List<UserGroupUser> userGroupUsers = userGroupUserMapper.selectByUserGroupId(Integer.valueOf(userGroupId));
		if(userGroupUsers.size()>0) {
			return false;
		}
		//删除用户组角色关联记录
		userGroupRoleMapper.deleteByRoleId(userGroupId);

		userGroupMapper.deleteByPrimaryKey(Integer.valueOf(userGroupId));
		if (userGroupUsers.size() > 0) {
			userGroupUserMapper.batchDelete(userGroupUsers);
		}


		return true;
	}

	/**
	 * 
	 * @ClassName: UserGroupService
	 * @Description:根据用户组id查询用户组信息
	 * @param userGroupId
	 */
	public UserInGroup getUserGroupId(Integer userGroupId) {
		List<User> list = new ArrayList<User>();
		// 根据用户组id查询用户组
		UserGroup userGroup = userGroupMapper.selectByPrimaryKey(userGroupId);
		// 根据查询的来的用户组中的人员列表
		List<UserGroupUser> userGroupUsers = userGroupUserMapper.selectByUserGroupId(userGroup.getUserGroupId());
		for (UserGroupUser userGroupUser : userGroupUsers) {
			User user = userMapper.selectByPrimaryKey(userGroupUser.getUserId());
			list.add(user);
		}
		// 给UserInGroup赋值
		UserInGroup userInGroup = new UserInGroup();
		userInGroup.setUserGroupId(userGroup.getUserGroupId());
		userInGroup.setUserGroupName(userGroup.getUserGroupName());
		userInGroup.setUserGroupDesc(userGroup.getUserGroupDesc());
		userInGroup.setUsers(list);
		return userInGroup;
	}

	/**
	 * 修改用户组
	 * 
	 * @param reqUserGroup
	 * @return
	 */
	@Transactional
	public boolean updateUserGroup(ReqUserGroup reqUserGroup,HttpServletRequest request) {
		// 添加用户组信息
		UserGroup userGroup = new UserGroup();
		userGroup.setUserGroupId(reqUserGroup.getUserGroupId());
		userGroup.setUserGroupName(reqUserGroup.getUserGroupName());
		userGroup.setUserGroupDesc(reqUserGroup.getUserGroupDesc());
		userGroupMapper.updateByPrimaryKeySelective(userGroup);
		return true;
	}

	/**
	 * 删除用户组下的用户
	 * 
	 * @param userGroupUser
	 * @return
	 */
	public Integer deleteUserGroupUser(UserGroupUser userGroupUser) {
		return userGroupUserMapper.deleteByUserGroupUserPrimaryKey(userGroupUser);
	}

	/**
	 * 查询所有人员
	 * 
	 * @param userListByUserGroupId
	 * @return
	 */
	public Page<User> getUserListByUserGroupId(UserListByUserGroupId userListByUserGroupId) {
		PageHelper.startPage(userListByUserGroupId.getPageCurrent(), userListByUserGroupId.getPageSize());
		Page<User> users = new Page<User>();
		if (userListByUserGroupId.getUserNames() == null) {
			users = userGroupUserMapper.selectUserListByUserGroupId(userListByUserGroupId.getUserGroupId());
		} else {
			users = userGroupUserMapper.selectUserListByUserGroupName(userListByUserGroupId);
		}
		return users;
	}

	/**
	 * 根据用户Id查询用户所在用户组Id
	 * 
	 * @param userId
	 * @return
	 */
	public List<UserGroup> getUserGroupByUserId(Integer userId) {
		return userGroupMapper.selectUserGroupByUserId(userId);
	}

	/**
	 * 部门下添加人员
	 * 
	 * @param reqUserGroup
	 * @return
	 */
	public boolean insertUserGroupUser(ReqUserGroup reqUserGroup) {
		List<UserGroupUser> ugrList = new ArrayList<>();
		for (String userId : reqUserGroup.getUsereIds()) {
			UserGroupUser userGroupUser = new UserGroupUser();
			userGroupUser.setUserGroupId(reqUserGroup.getUserGroupId());
			userGroupUser.setUserId(Integer.valueOf(userId));
			Integer user = userGroupUserMapper.selectByUserIdPrimaryKey(userGroupUser);
			if (user == null) {
				ugrList.add(userGroupUser);
			}
		}
		if (ugrList.size() > 0) {
			userGroupUserMapper.batchInsert(ugrList);
		}
		return true;
	}

}
